<template>
	<view class="steps-content">
		<uni-section title="录入步骤" type="line" padding>
			<uni-steps :options="steps" active-icon="checkbox" :active="activeStep" />
		</uni-section>
	</view>

	<view class="select-cropVariety" v-if="hasSelectedCrops === 0">
		<uni-card :is-shadow="false">
			<text class="uni-body">请选择品种及作物：</text>
			<uni-collapse accordion v-model="accordionVal">
				<uni-collapse-item v-for="(cropList, variety) in checkboxDataMap" :key="variety" :title="variety">
					<view class="uni-px-5 uni-pb-5">
						<uni-data-checkbox @change="onCropChange(variety)" multiple v-model="selectedCropIds[variety]"
							:localdata="cropList" />
					</view>
				</uni-collapse-item>
			</uni-collapse>
		</uni-card>
	</view>

	<view class="select-operation" v-if="hasSelectedCrops === 1">
		<uni-card>
			<uni-data-checkbox v-model="selectedCodeValue" :localdata="checkboxOptions" selectedColor="#007aff"
				@change="onOperationChange" />

			<view v-if="selectedOperation" class="">
				<view v-if="selectedOperation.value === '30036'">
					<uni-easyinput v-model="extraFields.reason" placeholder="请输入原因" />
				</view>
				<view v-else-if="selectedOperation.value === '30037'">
					<uni-easyinput v-model="extraFields.method" placeholder="请输入施肥方式" />
					<uni-easyinput v-model="extraFields.amount" placeholder="请输入施肥总量" />
					<uni-easyinput v-model="extraFields.fertilizerName" placeholder="请输入肥料名称" />
				</view>
			</view>
		</uni-card>
	</view>

	<view class="select-time" v-if="hasSelectedCrops === 2">
		<view class="time-item">
			<text class="label">开始时间</text>
			<uni-datetime-picker type="datetime" v-model="startTime" :clear-icon="false" :border="false"
				placeholder="请选择开始时间" :format="'yyyy-MM-dd HH:mm'" />
		</view>

		<view class="time-item">
			<text class="label">结束时间</text>
			<uni-datetime-picker type="datetime" v-model="endTime" :clear-icon="false" :border="false"
				placeholder="请选择结束时间" :format="'yyyy-MM-dd HH:mm'" />
		</view>
	</view>

	<view class="select-info" v-if="hasSelectedCrops === 3">
		<uni-card :is-shadow="false">

			<!-- 登录人选择 -->
			<view class="form-item">
				<text class="label">登录人</text>
				<uni-data-select v-model="selectedUser" :localdata="userOptions" placeholder="请选择登录人"
					:clear-icon="false" />
			</view>

			<!-- 操作状态 -->
			<view class="form-item">
				<text class="label">操作状态</text>
				<view class="status-group">
					<view v-for="item in statusOptions" :key="item.value" class="status-tag"
						:class="{ active: item.value === selectedStatus }" @click="selectedStatus = item.value">
						{{ item.text }}
					</view>
				</view>
			</view>

			<!-- 操作备注 -->
			<view class="form-item">
				<text class="label">操作备注</text>
				<uni-easyinput type="textarea" v-model="operationRemark" placeholder="请输入备注信息" autoHeight />
			</view>

		</uni-card>
	</view>


	<view class="select-bottom">
		<view class="button-row">
			<button v-if="hasSelectedCrops !== 0" type="default" @click="previousStep">上一步</button>
			<button v-if="hasSelectedCrops !== 3" type="primary" class="submit-btn" @click="nextStep">下一步</button>
			<button v-if="hasSelectedCrops === 3" type="primary" class="submit-btn" @click="onSubmitStep">提交</button>
		</view>
	</view>


</template>

<script setup>
	import {
		ref,
		computed
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app';

	const steps = [{
		title: '选择品种'
	}, {
		title: '操作'
	}, {
		title: '时间'
	}, {
		title: '其他'
	}];


	const activeStep = ref(0);
	const btStatus = ref(0);
	// 默认展开第一个品种
	const accordionVal = ref("0");

	// 原始作物数据
	const cropMap = ref({});
	const selectedCropIds = ref({});
	// 当前已选品种
	const currentVariety = ref('');
	const showCropSelector = ref(true)
	const hasSelectedCrops = ref(0);

	const operationList = ref([])

	const selectedCodeValue = ref('');
	const selectedOperation = ref({})

	const startTime = ref(null)
	const endTime = ref(null)

	const selectedUser = ref('')
	const operationRemark = ref('')
	const selectedStatus = ref('doing') // 默认选中“进行中”

	const userOptions = ref([{
			text: '张三',
			value: 'zhangsan'
		},
		{
			text: '李四',
			value: 'lisi'
		},
		{
			text: '王五',
			value: 'wangwu'
		}
	])

	const statusOptions = ref([{
			text: '进行中',
			value: 'doing'
		},
		{
			text: '已完成',
			value: 'done'
		},
		{
			text: '计划中',
			value: 'planned'
		}
	])

	const extraFields = ref({
		reason: '',
		method: '',
		amount: '',
		fertilizerName: ''
	})


	// 模拟接口加载
	function getCropData() {
		const res = {
			data: [{
					variety: '番茄',
					crops: [{
							id: 101,
							name: '桃太粉'
						},
						{
							id: 102,
							name: '阿鲁'
						},
						{
							id: 103,
							name: '福特斯'
						},
						{
							id: 104,
							name: '彩星1号'
						}
					]
				},
				{
					variety: '草莓',
					crops: [{
							id: 201,
							name: '红颜'
						},
						{
							id: 202,
							name: '章姬'
						},
						{
							id: 203,
							name: '甜查理'
						}
					]
				},
				{
					variety: '瓜果',
					crops: [{
							id: 301,
							name: '黄瓜'
						},
						{
							id: 302,
							name: '西瓜'
						},
						{
							id: 303,
							name: '甜瓜'
						}
					]
				},
				{
					variety: '水稻',
					crops: [{
							id: 401,
							name: '南粳9108'
						},
						{
							id: 402,
							name: '扬稻6号'
						}
					]
				}
			]
		}

		const map = {}
		const selected = {}
		res.data.forEach(item => {
			map[item.variety] = item.crops
			selected[item.variety] = []
		})
		cropMap.value = map;
		selectedCropIds.value = selected;
	}

	// 转换为 checkbox 所需格式
	const checkboxDataMap = computed(() => {
		const result = {}
		for (const variety in cropMap.value) {
			result[variety] = cropMap.value[variety].map(crop => ({
				text: crop.name,
				value: crop.id
			}))
		}
		return result
	})
	// 转换为 uni-data-checkbox 所需格式
	const checkboxOptions = computed(() =>
		operationList.value.map(item => ({
			text: item.name,
			value: item.codeValue
		}))
	)

	function fetchOperationList() {
		// 模拟接口返回
		const res = [{
				codeSortId: 121,
				codeValue: "30036",
				name: "整枝打杈",
				contentOne: "default,a_1,a_3,b_2,c_2,c_3,c_4,c_5,c_1,c_6",
				contentTwo: "#ff5583",
				contentThree: "",
				contentFour: "",
				contentFive: "",
				isValid: 1,
				flag: null
			},
			{
				codeSortId: 122,
				codeValue: "30037",
				name: "施肥",
				contentOne: "default,a_2,b_1,c_1,c_2,c_3",
				contentTwo: "#33cc99",
				contentThree: "",
				contentFour: "",
				contentFive: "",
				isValid: 1,
				flag: null
			},
			{
				codeSortId: 123,
				codeValue: "30038",
				name: "灌溉",
				contentOne: "default,b_3,c_1,c_2",
				contentTwo: "#3399ff",
				contentThree: "",
				contentFour: "",
				contentFive: "",
				isValid: 1,
				flag: null
			}
		]

		operationList.value = res
	}

	onLoad(() => {
		getCropData()
	})

	function change(e) {
		console.log(e);
	}

	function onCropChange(variety) {
		if (currentVariety.value && currentVariety.value !== variety) {
			for (const key in selectedCropIds.value) {
				if (key !== variety) {
					selectedCropIds.value[key] = []
				}
			}
		}
		currentVariety.value = variety
	}

	function previousStep() {
		if (activeStep.value === 1) {
			activeStep.value = 0;
			hasSelectedCrops.value = 0;
		} else if (activeStep.value === 2) {
			activeStep.value = 1;
			hasSelectedCrops.value = 1;
		} else {
			activeStep.value = 2;
			hasSelectedCrops.value = 2;
		}
	}

	function nextStep() {
		if (activeStep.value === 0) {
			const selected = selectedCropIds.value[currentVariety.value];
			if (!selected || selected.length === 0) {
				uni.showToast({
					title: '请至少选择一个作物',
					icon: 'none'
				})
				return
			}
			console.log('选中的作物 ID：', selected)
			activeStep.value = 1;
			hasSelectedCrops.value = 1;
			fetchOperationList();
		} else if (activeStep.value === 1) {
			console.log(selectedOperation.value.value)
			if (selectedOperation.value.value == null) {
				uni.showToast({
					title: '请选择一个操作类型',
					icon: 'none'
				})
				return
			}
			activeStep.value = 2;
			hasSelectedCrops.value = 2;
		} else if (activeStep.value === 2) {
			if (startTime.value === null) {
				uni.showToast({
					title: '请选择开始时间',
					icon: 'none'
				})
				return
			}
			if (endTime.value === null) {
				uni.showToast({
					title: '请选择结束时间',
					icon: 'none'
				})
				return
			}
			console.log(startTime.value)
			console.log(endTime.value)
			activeStep.value = 3;
			hasSelectedCrops.value = 3;
		}

	}

	// 选中操作项后更新状态
	function onOperationChange(codeValue) {
		selectedOperation.value = codeValue.detail.data
	}

	function onSubmitStep() {
		// 提交完成后关闭当前页面
		uni.navigateBack()
	}
</script>

<style lang="scss" scoped>
	.select-cropVariety {}

	.select-bottom {

		padding: 0 30rpx;

		.select-bottom {
			padding: 30rpx;
		}

		.button-row {
			display: flex;
			gap: 20rpx;
		}

		.submit-btn {
			flex: 3;
		}

		.reset-btn {
			flex: 1;
		}

	}

	.select-time {
		padding: 20rpx;

		.time-item {
			margin-bottom: 20rpx;

			.label {
				display: inline-block;
				margin-bottom: 10rpx;
				font-size: 28rpx;
				color: #333;
			}
		}
	}

	.select-info {
		.form-item {
			margin-bottom: 30rpx;
		}

		.label {
			font-size: 28rpx;
			color: #333;
			margin-bottom: 10rpx;
			display: block;
		}

		.status-group {
			display: flex;
			gap: 20rpx;
			margin-top: 10rpx;
		}

		.status-tag {
			padding: 12rpx 24rpx;
			border-radius: 30rpx;
			background-color: #f0f0f0;
			color: #666;
			font-size: 26rpx;
		}

		.status-tag.active {
			background-color: #007aff;
			color: #fff;
		}

	}
</style>